// 表单
import type { TemplateFormConfig } from '#/views/onlineDesign/designPage/template/type/type';

import { z } from '@vben/common-ui';

import { querySelectTableApi } from '#/api';
import { queryDictOptionsApi } from '#/utils';
import { tableConfig } from '#/views/onlineDesign/designPage/template/tableTemplate/config';

type FormComponentOptionType =
  | 'ApiSelectDict'
  | 'ApiSelectTable'
  | 'DatePicker'
  | 'Input'
  | 'InputNumber'
  | 'InputPassword'
  | 'RangePicker'
  | 'Textarea'
  | 'TimePicker';

/**
 * 组装表单组件属性方法
 */
const formComponentOptionFun = {
  getComponentOption: (componentType: FormComponentOptionType, params: any) => {
    switch (componentType) {
      case 'ApiSelectDict': {
        tableConfig.formConfig.baseConfig.dict = true;
        return {
          ...params.commonProps,
          component: 'ApiSelect',
          componentProps: {
            ...params.componentProps,
            afterFetch: (data) =>
              data.map(({ itemText, itemVal }) => ({
                label: itemText,
                value: params.dataType ? Number.parseInt(itemVal) : itemVal,
              })),
            api: queryDictOptionsApi,
            params: { dictCode: params.dictCode },
          },
        } as TemplateFormConfig.FormComponentConfig;
      }
      case 'ApiSelectTable': {
        tableConfig.formConfig.baseConfig.table = true;
        return {
          ...params.commonProps,
          component: 'ApiSelect',
          componentProps: {
            ...params.componentProps,
            api: querySelectTableApi,
            params: {
              tableName: params.tableName,
              labelField: params.labelField,
              valueField: params.valueField,
              sqlSelect: 'del_flag = 0',
            },
          },
        } as TemplateFormConfig.FormComponentConfig;
      }
      case 'DatePicker': {
        return {
          ...params.commonProps,
          component: 'DatePicker',
          componentProps: {
            placeholder: `请选择${params.placeholder}`,
          },
        } as TemplateFormConfig.FormComponentConfig;
      }
      case 'Input': {
        return {
          ...params.commonProps,
          component: 'Input',
          componentProps: {
            placeholder: `请输入${params.placeholder}`,
          },
        } as TemplateFormConfig.FormComponentConfig;
      }
      case 'InputNumber': {
        return {
          ...params.commonProps,
          component: 'InputNumber',
          componentProps: {
            placeholder: `请输入${params.placeholder}`,
          },
        } as TemplateFormConfig.FormComponentConfig;
      }
      case 'InputPassword': {
        return {
          ...params.commonProps,
          component: 'InputPassword',
          componentProps: {
            placeholder: `请输入${params.placeholder}`,
          },
        } as TemplateFormConfig.FormComponentConfig;
      }
      case 'RangePicker': {
        return {
          ...params.commonProps,
          component: 'RangePicker',
          componentProps: {
            placeholder: `请选择${params.placeholder}`,
          },
        } as TemplateFormConfig.FormComponentConfig;
      }
      case 'Textarea': {
        return {
          ...params.commonProps,
          component: 'Textarea',
          componentProps: {
            placeholder: `请输入${params.placeholder}`,
          },
        } as TemplateFormConfig.FormComponentConfig;
      }
      case 'TimePicker': {
        return {
          ...params.commonProps,
          component: 'TimePicker',
          componentProps: {
            placeholder: `请选择${params.placeholder}`,
          },
        } as TemplateFormConfig.FormComponentConfig;
      }
    }
  },
};

/**
 * 组装表单方法
 */
export const formFun = {
  /**
   * 获取组件
   * @param field 字段
   * @param commonProps 通用信息
   */
  getComponent: (
    field: Array,
    commonProps: TemplateFormConfig.FormComponentConfig,
  ) => {
    // 校验规则
    const rule = isRules(field);
    const updatedCommonProps = {
      ...commonProps,
      ...(rule === undefined ? {} : { rules: rule }),
    };
    switch (field.componentName) {
      // 下拉框
      case 'ApiSelect': {
        // （关联（0否 1是））
        if (field.fieldRelevance === 1) {
          // 是字典下拉还是表下拉
          const apiProps = {
            allowClear: true,
            placeholder: `请选择${field.fieldAnnotation}`,
          };
          // 关联模式（0关联模型 1关联字典）
          if (field.fieldRelevanceMode === 1) {
            return formComponentOptionFun.getComponentOption('ApiSelectDict', {
              commonProps: updatedCommonProps,
              componentProps: apiProps,
              // 数据类型转换
              dataType: field.fieldPackagePath.includes('Integer'),
              dictCode: field.fieldRelevanceModeValKey,
            });
          } else if (field.fieldRelevanceMode === 0) {
            return formComponentOptionFun.getComponentOption('ApiSelectTable', {
              commonProps: updatedCommonProps,
              componentProps: apiProps,
              tableName: field.fieldRelevanceModeModelCode,
              labelField: field.fieldRelevanceModeValKey,
              valueField: field.fieldRelevanceModeModelField,
            });
          }
        }
        return formComponentOptionFun.getComponentOption('Input', {
          commonProps: updatedCommonProps,
          placeholder: field.fieldAnnotation,
        });
      }
      case 'DatePicker': {
        return formComponentOptionFun.getComponentOption('DatePicker', {
          commonProps: updatedCommonProps,
          placeholder: field.fieldAnnotation,
        });
      }
      // 输入框
      case 'Input': {
        return formComponentOptionFun.getComponentOption('Input', {
          commonProps: updatedCommonProps,
          placeholder: field.fieldAnnotation,
        });
      }
      // 数字输入框
      case 'InputNumber': {
        return formComponentOptionFun.getComponentOption('InputNumber', {
          commonProps: updatedCommonProps,
          placeholder: field.fieldAnnotation,
        });
      }
      // 密码框
      case 'InputPassword': {
        return formComponentOptionFun.getComponentOption('InputPassword', {
          commonProps: updatedCommonProps,
          placeholder: field.fieldAnnotation,
        });
      }
      case 'RangePicker': {
        return formComponentOptionFun.getComponentOption('RangePicker', {
          commonProps: updatedCommonProps,
          placeholder: field.fieldAnnotation,
        });
      }
      case 'Textarea': {
        return formComponentOptionFun.getComponentOption('Textarea', {
          commonProps: updatedCommonProps,
          placeholder: field.fieldAnnotation,
        });
      }
      case 'TimePicker': {
        return formComponentOptionFun.getComponentOption('TimePicker', {
          commonProps: updatedCommonProps,
          placeholder: field.fieldAnnotation,
        });
      }
    }
  },
};

/**
 * 校验判断
 * @param field 信息
 */
function isRules(field) {
  if (field.fieldRule === 0) {
    return undefined;
  }
  const type = field.fieldPackagePath.includes('Integer');
  let schema = type ? z.number() : z.string();
  // 非空校验（0否 1是）
  const notNullRule = field.fieldRuleNotNull === 1;
  // 长度校验
  const minLengthRule = field.fieldRuleMin !== 0;
  const maxLengthRule = field.fieldRuleMax !== 0;
  // 自定义正则校验（0否 1是）
  const regularRule = field.field_rule_regular === 1;
  if (notNullRule) {
    // 非空校验，判断是否存在长度和正则校验
    if (minLengthRule || maxLengthRule || regularRule) {
      if (minLengthRule) {
        schema = schema.min(
          field.fieldRuleMin,
          `${field.fieldAnnotation}最少${field.fieldRuleMin}字符`,
        );
      }
      if (maxLengthRule) {
        schema = schema.max(
          field.fieldRuleMax,
          `${field.fieldAnnotation}最多${field.fieldRuleMax}字符`,
        );
      }
    } else {
      return 'required';
    }
  } else {
    if (minLengthRule) {
      schema = schema.min(
        field.fieldRuleMin,
        `${field.fieldAnnotation}最少${field.fieldRuleMin}字符`,
      );
    }
    if (maxLengthRule) {
      schema = schema.max(
        field.fieldRuleMax,
        `${field.fieldAnnotation}最多${field.fieldRuleMax}字符`,
      );
    }
    schema.optional();
  }
  return schema;
}
